package com.xxx.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBManager {
	
	public static Connection conn() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = 
					DriverManager.getConnection("jdbc:mysql://39.107.242.249:3306/XueXi?useUnicode=true&characterEncoding=UTF-8",
							"root","admin");
			return connection;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace() ;
		}
		 return null;
	}
	
	public static int executeUpdate(String sql) {
		Connection connection = conn();
		Statement statement = null;
		try {
			statement = connection.createStatement();
		    int result = statement.executeUpdate(sql);
		    return result;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll(null, statement, connection);
		}
		return 0;
	}
	
	public static QueryDataResult executeQuery(String sql) {
		Statement statement = null;
		Connection connection = conn();
		ResultSet rSet = null;
		try {
		    statement = connection.createStatement();
		    rSet = statement.executeQuery(sql);
		    return new QueryDataResult(rSet, connection, statement);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			closeAll(rSet, statement, connection);
			return null;
		}	
	}
	
	public static void closeAll(ResultSet resultSet,Statement statement,Connection connection) {
		try {
			if(resultSet!=null) {
				resultSet.close();
			}
			if(statement!=null) {
				statement.close();
			}
			if(connection!=null) {
			connection.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
